package com.chaodriod.flyviewpager.indicator

import android.support.v4.util.SparseArrayCompat
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import com.chaodriod.flyviewpager.CustomViewPager
import com.chaodriod.flyviewpager.indicator.adapter.IndicatorAdapter
import com.chaodriod.flyviewpager.indicator.listener.IndicatorSelectListener

/**
 * Created by CHEN on 2018-5-7.
 */
open class IndicatorView(val mViewPager: ViewPager, private val mIndicatorAdapter: IndicatorAdapter, private val mListener: IndicatorSelectListener) : Indicator {

    var mIndicators: SparseArrayCompat<View?> = SparseArrayCompat()
    var mCurrentPosition: Int = 0
    var mAdapter: IndicatorAdapter = object : IndicatorAdapter {
        override fun getIndicatorView(position: Int): View {
            val indicatorView: View = getItem(position)
            indicatorView.setOnClickListener {
                setCurrentItem(position)
                if (mViewPager is CustomViewPager) {
                    mViewPager.setCurrentItem(position, mViewPager.isCanScroll)
                } else {
                    mViewPager.setCurrentItem(position, true)
                }
            }
            return indicatorView
        }
    }

    init {
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            override fun onPageSelected(position: Int) {
                setCurrentItem(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }
        })
    }

    override fun init(container: ViewGroup) {
        val count = mViewPager.adapter?.count ?: 0
        for (i: Int in 0 until count) {
            container.addView(mAdapter.getIndicatorView(i))
        }
        setCurrentItem(mCurrentPosition)
    }

    override fun setCurrentItem(position: Int) {
        mListener.onSelected(position, mCurrentPosition)
        mCurrentPosition = position
    }

    override fun getItem(position: Int): View {
        return if (mIndicators.get(position) != null) {
            mIndicators.get(position)!!
        } else {
            val view = mIndicatorAdapter.getIndicatorView(position)
            mIndicators.put(position, view)
            view
        }
    }

    override fun getAdapter(): IndicatorAdapter {
        return mAdapter
    }

}